package com.leruan.aasimp.action.forum;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.constant.UsedCarConstant;
import com.leruan.aasimp.entity.Board;
import com.leruan.aasimp.entity.Forumuser;
import com.leruan.aasimp.entity.Mainpost;
import com.leruan.aasimp.entity.Reply;
import com.leruan.aasimp.entitydto.MainPostDto;
import com.leruan.aasimp.entitydto.ReplyDto;
import com.leruan.aasimp.entitydto.StaticStrings;
import com.leruan.aasimp.service.BoardService;
import com.leruan.aasimp.service.ForumUserService;
import com.leruan.aasimp.service.MainPostService;
import com.leruan.aasimp.service.ReplyService;
import com.leruan.aasimp.util.ArticleUtils;
import com.leruan.aasimp.util.Validators;
import com.opensymphony.xwork2.ActionSupport;

public class ForumAction extends ActionSupport {

    /**
     * 
     * 
     */
    private static final long serialVersionUID = 4792613008361483033L;
    @Resource
    private BoardService boardService;
    @Resource
    private ForumUserService forumUserService;
    @Resource
    private MainPostService mainPostService;
    @Resource
    private ReplyService replyService;

    private List<Board> boards = new ArrayList<Board>();
    private Board board;
    public Map<String, Forumuser> forumuserMap = new HashMap<String, Forumuser>();
    public Map<String, String> forumuserNameMap = new HashMap<String, String>();
    public Map<String, String> lastPostUserMap = new HashMap<String, String>();
    public Map<String, Date> lastPostTimeMap = new HashMap<String, Date>();
    private String boardId;// 板块ID
    private String postId;
    private Forumuser forumuser;
    private Forumuser lastuser;
    private Mainpost mainpost;
    public List<Mainpost> mainPosts = new ArrayList<Mainpost>();// 帖子列表
    private List<Mainpost> newMainPosts = new ArrayList<Mainpost>();
    private List<Mainpost> popularMainPosts = new ArrayList<Mainpost>();
    private List<Mainpost> newEssenceMainPosts = new ArrayList<Mainpost>();
    private List<ReplyDto> replyList = new ArrayList<ReplyDto>();
    private final Map<String, Forumuser> forumuserList = new HashMap<String, Forumuser>();

    private String userId;
    private String postTitle;
    private String content;
    private Date postDate;
    private Date modifyDate;
    public String fileName = "";
    private Map<String, String> brandMap;
    public StringBuffer brands = new StringBuffer();

    // 进入论坛首页
    public String index() {
        boards = boardService.getBoard();// 板块
        HttpServletRequest request = ServletActionContext.getRequest();
        for (Board b : boards) {
            forumuser = forumUserService.getBoardUserById(b.getBoardUserId());
            forumuserMap.put(b.getBoardUserId(), forumuser);// 版主map
        }
        getnewMainPosts();// 获取最新发布的帖子（最新发表）
        getPopularPosts(); // 获取最受欢迎的帖子（热门主题）
        getNewEssencePosts();// 获取最新精华帖子（最新精华）
        request.setAttribute("boards", boards);
        request.setAttribute("forumuserMap", forumuserMap);
        request.setAttribute("newMainPosts", newMainPosts);
        request.setAttribute("popularMainPosts", popularMainPosts);
        request.setAttribute("newEssenceMainPosts", newEssenceMainPosts);
        return "success";
    }

    private void getNewEssencePosts() {
        newEssenceMainPosts = mainPostService.getMainPostsNewEssence();
    }

    private void getPopularPosts() {
        popularMainPosts = mainPostService.getMainPostsPopular();
    }

    private void getnewMainPosts() {
        newMainPosts = mainPostService.getMainPostsNewest();
    }

    // 帖子详情
    public String viewPost() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        System.out.println("1");
        postId = request.getParameter("postId");
        if (Validators.isEmpty(postId)) {
            return "success";
        }
        mainpost = mainPostService.getMainPostsByPostId(postId);
        mainpost.setHits(mainpost.getHits() + 1);
        mainPostService.modifyMainPost(mainpost);
            String filePath = StaticStrings.FILEPATH;
            filePath = filePath + mainpost.getContent();
            mainpost.setContent(ArticleUtils.readArticleFromFile(filePath));
        if (mainpost == null) {
            return "success";
        }
        Forumuser forumuser = forumUserService.getBoardUserById(mainpost.getUserId());// 这个方法名字取得不怎么好
        getBoardList();

        int pageNo = 1;
        try {
            getReplyAndUserListByPostId(postId, pageNo);// 获得回复和回复者列表
            Long total = mainpost.getReplyNum();
            board = boardService.getBoardById(mainpost.getBoardId());
            request.setAttribute("board", board);
            request.setAttribute("boards", boards);
            request.setAttribute("mainpost", mainpost);
            request.setAttribute("replyList", replyList);
            request.setAttribute("forumuserList", forumuserList);
            request.setAttribute("forumuser", forumuser);
            session.setAttribute("pageNoSale", pageNo);
            session.setAttribute("pageNoCenterSale", 3);
            session.setAttribute("totalNoSale", total / UsedCarConstant.PAGE_SIZE + 1);
            session.setAttribute("totalSale", total);
        }
        catch (Exception e) {
            e.printStackTrace();

        }
        return "success";
    }

    public String viewPostQuery() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        postId = request.getParameter("postId");
        int pageNo = Integer.parseInt(request.getParameter("no"));
        getBoardList();
        mainpost = mainPostService.getMainPostsByPostId(postId);
        String filePath = StaticStrings.FILEPATH;
        filePath = filePath + mainpost.getContent();
        mainpost.setContent(ArticleUtils.readArticleFromFile(filePath));
	    if (mainpost == null) {
	        return "success";
	    }
        Forumuser forumuser = forumUserService.getBoardUserById(mainpost.getUserId());// 这个方法名字取得不怎么好
        board = boardService.getBoardById(mainpost.getBoardId());
        try {
            getReplyAndUserListByPostId(postId, pageNo);
            request.setAttribute("board", board);
            request.setAttribute("mainpost", mainpost);
            request.setAttribute("boards", boards);
            request.setAttribute("replyList", replyList);
            request.setAttribute("forumuser", forumuser);
            request.setAttribute("forumuserList", forumuserList);
            session.setAttribute("pageNoSale", pageNo);
            Long total = (Long) session.getAttribute("totalNoSale");
            if (pageNo < 3 || total < 5) {
                session.setAttribute("pageNoCenterSale", 3);
            }
            else if (pageNo > total - 2) {
                session.setAttribute("pageNoCenterSale", total - 2);
            }
            else {
                session.setAttribute("pageNoCenterSale", pageNo);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    public String userDetails() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String userId = request.getParameter("userId");
        Forumuser forumuserDetail = forumUserService.getForumUserByUsername(username);
        Long replyNum = replyService.getReplyNumberById(userId);
        Long mainPostNum = mainPostService.getMainPostNumById(userId);

        int pageNo = 1;
        try {
            List<MainPostDto> mainPosts = mainPostService.getMainPostsByUserId(userId, pageNo);
            Long total = mainPostNum;
            request.setAttribute("forumuserDetail", forumuserDetail);
            request.setAttribute("mainPosts", mainPosts);
            request.setAttribute("replyNum", replyNum);
            request.setAttribute("mainPostNum", mainPostNum);
            session.setAttribute("pageNoSale", pageNo);
            session.setAttribute("pageNoCenterSale", 3);
            session.setAttribute("totalNoSale", total / UsedCarConstant.PAGE_SIZE + 1);
            session.setAttribute("totalSale", total);
        }
        catch (Exception e) {
            e.printStackTrace();

        }

        return "success";
    }

    public String userDetailsQuery() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String userId = request.getParameter("userId");
        int pageNo = Integer.parseInt(request.getParameter("no"));
        Forumuser forumuserDetail = forumUserService.getForumUserByUsername(username);
        Long replyNum = replyService.getReplyNumberById(userId);
        Long mainPostNum = mainPostService.getMainPostNumById(userId);
        try {
            List<MainPostDto> mainPosts = mainPostService.getMainPostsByUserId(userId, pageNo);
            request.setAttribute("forumuserDetail", forumuserDetail);
            request.setAttribute("mainPosts", mainPosts);
            request.setAttribute("replyNum", replyNum);
            request.setAttribute("mainPostNum", mainPostNum);
            session.setAttribute("pageNoSale", pageNo);
            Long total = (Long) session.getAttribute("totalNoSale");
            if (pageNo < 3 || total < 5) {
                session.setAttribute("pageNoCenterSale", 3);
            }
            else if (pageNo > total - 2) {
                session.setAttribute("pageNoCenterSale", total - 2);
            }
            else {
                session.setAttribute("pageNoCenterSale", pageNo);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    private void getReplyAndUserListByPostId(String postId, int pageNo) {
        List<String> ids = new ArrayList<String>();
        Forumuser forumuser = new Forumuser();
        replyList = replyService.getReplyByPostId(postId, null, pageNo);
        for (Reply r : replyList) {
            forumuser = forumUserService.getBoardUserById(r.getUserId());
            forumuserList.put(r.getUserId(), forumuser);
        }

    }

    private void getBoardList() {
        boards = boardService.getBoard();
    }

    public BoardService getBoardService() {
        return boardService;
    }

    public void setBoardService(BoardService boardService) {
        this.boardService = boardService;
    }

    public ForumUserService getForumUserService() {
        return forumUserService;
    }

    public void setForumUserService(ForumUserService forumUserService) {
        this.forumUserService = forumUserService;
    }

    public MainPostService getMainPostService() {
        return mainPostService;
    }

    public void setMainPostService(MainPostService mainPostService) {
        this.mainPostService = mainPostService;
    }

    public ReplyService getReplyService() {
        return replyService;
    }

    public void setReplyService(ReplyService replyService) {
        this.replyService = replyService;
    }

    public List<Board> getBoards() {
        return boards;
    }

    public void setBoards(List<Board> boards) {
        this.boards = boards;
    }

    public String getBoardId() {
        return boardId;
    }

    public void setBoardId(String boardId) {
        this.boardId = boardId;
    }

    public Board getBoard() {
        return board;
    }

    public void setBoard(Board board) {
        this.board = board;
    }

}
